﻿(function ($) {
    $.fn.NodeBrowser = function (settings) {
        var res = this; //jquery object//context
        res.settings = settings;
        res.ui = res.find(".nb_content");
        res.uiparent = res.find(".nb_current");
        res.panel = res.find(".nb_panel");
        res.Add = function (node) { return NotYetImplemented('Add(node, res)'); };
        res.Change = function (node) { return NotYetImplemented('Change(node, res)'); };
        res.Up = function (node) { return NotYetImplemented('Up(node, res)'); };
        res.Down = function (node) { return NotYetImplemented('Down(node, res)'); };
        res.Delete = function (node) { return Delete(node, res); };
        res.Edit = function (node) { return NotYetImplemented('Edit(node, res)'); };
        res.Refresh = function () { return ShowNodeInfo(res.settings.id, res); };

        res.Refresh();
        return res;
    };
    function NotYetImplemented(title) {
        UmbClientMgr.mainWindow().UmbSpeechBubble.ShowMessage('warning', title ? title : 'not yet implemented!', 'This functionality haven\'t been implemented yet!');
    }

    function Delete(node, o) {
        //check if it's in the recycle bin
        //        /if (actionNode.jsNode.closest("li[id='-20']").length == 1 || actionNode.jsNode.closest("li[id='-21']").length == 1) {
        //            umbraco.presentation.webservices.legacyAjaxCalls.DeleteContentPermanently(
        //                        UmbClientMgr.mainTree().getActionNode().nodeId,
        //                        UmbClientMgr.mainTree().getActionNode().nodeType,
        //                        function () {
        //                            _this._debug("actionDelete: Raising event");
        //                            //raise nodeDeleted event
        //                            jQuery(window.top).trigger("nodeDeleted", []);
        //                        });
        //        }
        //        else {
        //        var m = UmbClientMgr;
        //        m.webservices.legacyAjaxCalls.Delete(
        //                        node.data, "", node.type,
        //                        function () {
        //                            _this._debug("actionDelete: Raising event");
        //                            //raise nodeDeleted event
        //                            jQuery(window.top).trigger("nodeDeleted", []);
        //                        },
        //                        function (error) {
        //                            _this._debug("actionDelete: Raising public error event");
        //                            //raise public error event
        //                            jQuery(window.top).trigger("publicError", [error]);
        //                        })
        //        //}
    };

    function ShowNodeInfo(nid, o) {
        o.ndata = { info: nid, data: nid, type: "content" };
        ShowNodeContent(o.ndata, o);
        $.ajax({
            url: '/umbraco/webservices/TreeNodeData.ashx?rndo=' + uuidFast() + '',
            dataType: 'json',
            data: o.ndata,
            success: function (d, s, j) {
                o.ndata = { info: d, data: nid, type: "content" };
                GetNodePath(o.ndata, function (node) {
                    o.uiparent.find("li").remove();
                    o.ndata.node = DataToNode(o.ndata.info);
                    o.ndata.node.appendTo(o.uiparent);
                    o.ndata.Path = "";
                    $(o.ndata.info.parents).each(function (p, pitem) {
                        if (pitem["info"]) node.Path = node.Path + "/" + pitem["info"].name;
                    });
                    o.ndata.node.ntitle.html('');
                    o.ndata.node.npath = $("<span class='npath' style=''>" + node.Path + "</span>");
                    o.ndata.node.npath.appendTo(o.ndata.node.ntitle);
                    if (node.info.icon) {
                        if (node.info.icon[0] == ".") o.ndata.node.npath.addClass(node.info.icon.substring(1, node.info.icon.length));
                        else o.ndata.node.npath.css("background-image", "url(/umbraco/images/umbraco/" + node.info.icon);
                    };
                    o.ndata.node.attr("title", "[" + String(o.ndata.data) + "] " + o.ndata.node.Path + " (" + String(o.ndata.type) + ")");
                });
            },
            error: function () {
                //el.addClass("error");
                o.ndata.node = {};
            }
        });
    }
    function ShowNodeContent(ndata, o) {
        $.ajax({
            type: "GET",
            url: '/umbraco/webservices/TreeDataService.ashx',
            dataType: 'json',
            data: { contextmenu: false, dialogMode: "id", id: ndata.data, isDialog: true, treeType: ndata.type, rnd: uuidFast() },
            success: function (d, s, j) {
                $(d).each(function (p, cnode) {
                    var rdata = { type: "content", data: cnode.attributes.id, info: { icon: cnode.data.icon }, title: cnode.data.title };
                    var el = DataToNode(rdata, o);
                    el.appendTo(o.ui);
                    el.ntitle.html('');
                    el.npath = $("<span class='npath' style=''>" + rdata.title + "</span>");
                    el.npath.appendTo(el.ntitle);
                    if (rdata.info.icon) {
                        if (rdata.info.icon[0] == ".") el.npath.addClass(rdata.info.icon.substring(1, rdata.info.icon.length));
                        else el.npath.css("background-image", "url(" + rdata.info.icon);
                    } else {
                        if (cnode.data.attributes.class) el.npath.addClass(cnode.data.attributes.class);
                    }
                    el.pos.text(Number(el.index()) + 1);
                    el.npath.hover(function () {
                        el.pos.text(Number(el.index()) + 1);
                        el.pos.addClass("highlighten");
                    }, function () {
                        el.pos.removeClass("highlighten");
                    });
                    el.npath.click(function () { o.Change(rdata); });
                    ShowUpDown(el, rdata, o);
                    ShowEditDelete(el, rdata, o);
                    el.attr("title", "[" + String(rdata.data) + "] " + rdata.title + " (" + String(rdata.type) + ")");
                });
            }
        });
    }

    function ShowUpDown(linode, ndata, o) {
        linode.nbupdown.html("<img class='bup' src='/umbraco/ism/fields/dynamictreepicker/images/b_up.png'/><img class='bdown' src='/umbraco/ism/fields/dynamictreepicker/images/b_down.png'/>");
        linode.bup = linode.nbupdown.find(".bup");
        linode.bup.click(function () { o.Up(ndata); });
        linode.bdown = linode.nbupdown.find(".bdown");
        linode.bdown.click(function () { o.Down(ndata); });
    }

    function ShowEditDelete(linode, ndata, o) {
        linode.nbdelchg.html("<img class='bchng' src='/umbraco/ism/fields/dynamictreepicker/images/b_change.png' tilte='click to choose other one...' alt='chage " + ndata.type + "...'/><img class='bdel' src='/umbraco/ism/fields/dynamictreepicker/images/b_delete.png' alt='delete this from list...'/><img class='bedit' src='/umbraco/ism/fields/dynamictreepicker/images/b_edit.png' alt='edit'/>");
        linode.bchage = linode.nbdelchg.find(".bchng");
        linode.bchage.click(function () { o.Change(ndata); });
        linode.bdel = linode.nbdelchg.find(".bdel");
        linode.bdel.click(function () { o.Delete(ndata); });
        linode.bedt = linode.nbdelchg.find(".bedit");
        linode.bedt.click(function () { o.Edit(ndata); });
    }

    function GetNodePath(node, callBack) {
        var path = node.info.name;
        var l = node.info.parents ? node.info.parents.length : 0;
        $(node.info.parents).each(function (p, pitem) {
            $.ajax({
                url: '/umbraco/webservices/TreeNodeData.ashx?rndo=' + uuidFast() + '',
                dataType: 'json',
                data: { type: node.type, data: pitem },
                success: function (d, s, j) {
                    node.info.parents[p] = { info: d };
                    l--;
                    if (l <= 0) callBack(node);
                },
                error: function () {
                    l--;
                    if (l <= 0) callBack(node);
                }
            });
        });
    }

    function DataToNode(data, o) {
        var linode = $("<li><span class='npos'><!--a--></span><span class='chgdel'><!--cd--></span><input type=\"hidden\" class=\"ntype\" value=\"\" /><input type=\"hidden\" class=\"nval\" value=\"\" /><span class='updwn'><!----></span><span class=\"ntitle\"><!--t--></span></li>");
        linode.ntype = linode.find(".ntype"); linode.ntype.val(data.type);
        linode.nval = linode.find(".nval"); linode.nval.val(data.data);
        linode.ntitle = linode.find(".ntitle"); linode.ntitle.html(data.title ? data.title : data.data);
        linode.nbupdown = linode.find(".updwn");
        linode.nbdelchg = linode.find(".chgdel");
        linode.pos = linode.find(".npos");
        return linode;
    };
    function uuidFast() {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''), uuid = new Array(36), rnd = 0, r;
        for (var i = 0; i < 36; i++) {
            if (i == 8 || i == 13 || i == 18 || i == 23) {
                uuid[i] = '-';
            } else if (i == 14) {
                uuid[i] = '4';
            } else {
                if (rnd <= 0x02) rnd = 0x2000000 + (Math.random() * 0x1000000) | 0;
                r = rnd & 0xf;
                rnd = rnd >> 4;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
        var s = uuid.join('').replace(/-/g, "");
        return s;
    }
    function TransformTemplate(template, el, asObject) {
        var obj = this;
        var res = String(template);
        for (var pname in el) {
            res = res.replace(new RegExp("##" + pname + "##", "g"), el[pname]);
        }
        res = res.replace(new RegExp("##[^##]*##", "g"), ""); //replace rest to empty string
        return asObject ? { 'result': res, 'template': template, 'data': el} : res;
    }
})(jQuery);
